<?php 
namespace Application;

use Zend\Http\Header\Location;

use Zend\Mvc\ModuleRouteListener,
    Zend\Mvc\MvcEvent,
    Zend\ModuleManager\ModuleManager;
use Zend\Authentication\AuthenticationService,
    Zend\Authentication\Storage\Session as SessionStorage;

use Application\Service\UsuarioService as UsuarioService,
    Application\Auth\Adapter as AuthAdapter,
	Application\Acl\Autorizacao as Autorizacao,
	Application\Acl\PluginAutorizacao as PluginAutorizacao,
	Application\View\Helper\Menu,
	Application\View\Helper\Criptografia;
use Application\Service\FuncaoAtividadeService;

class Module {

    public function onBootstrap(MvcEvent $e) {
    	$eventManager = $e->getApplication()->getEventManager();
    	//$eventManager->attach(MvcEvent::EVENT_DISPATCH, array($this, 'mvcPreDispatch'),0);
// 		$eventManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, function(MvcEvent $event) {
// 		    $viewModel = $event->getViewModel();
// 		    $viewModel->setTemplate('error/404');
// 		}, -200);
    	
        $e->getApplication()
                ->getEventManager()
                ->getSharedManager()
                ->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
        			$controller = $e->getTarget();
        			$routeName = $e->getRouteMatch()->getMatchedRouteName(); 
        			
                    $config = $e->getApplication()->getServiceManager()->get('config');
                            if (isset($config['route_layouts'][$routeName])) {
                            	$controller->layout($config['route_layouts'][$routeName]);
                            }
                        }, 1);
                        
    }

    /**
     * Retorna Arquivo de Configuração do Módulo
     * @return Arquivo de Configuração
     */
    public function getConfig() {
        return include __DIR__ . '/config/module.config.php';
    }

    /**
     * Retorna os Namespaces
     * @return array de NamesSpaces
     */
    public function getAutoloaderConfig() {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ . 'Application' => __DIR__ . '/src/' . __NAMESPACE__ . "Application",
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    /**
     * Verifica Se o Usuário esta logado
     * @param \Sisesporte\ModuleManager $moduleManager
     * @return type
     */
    public function init(ModuleManager $moduleManager) {
//         $sharedEvents = $moduleManager->getEventManager()->getSharedManager();
//         $sharedEvents->attach("Geccal", 'dispatch', function($e) {
//                     $auth = new AuthenticationService();
//                     $auth->setStorage(new SessionStorage("Geccal"));

//                     $controller = $e->getTarget();
//                     $matchedRoute = $controller->getEvent()->getRouteMatch()->getMatchedRouteName();
//                     var_dump($matchedRoute);

//                     if (!$auth->hasIdentity() and ($matchedRoute == "sisesporte-admin" or $matchedRoute == "sisesporte-admin-interna")) {
//                         return $controller->redirect()->toRoute('home');
//                     }
//                 }, 99);
    }

    /**
     * Registra Servicos
     * @return array Service
     */
    public function getServiceConfig() {
        return array(
            'factories' => array(
                'Application\Service\UsuarioService' => function($service) {
                return new UsuarioService($service->get('Doctrine\ORM\EntityManager'));
                },
                'Application\Auth\Adapter' => function ($service){
                return new AuthAdapter($service->get('Doctrine\ORM\EntityManager'));
                },
                'Application\Acl\Autorizacao' => function ($service){
                	return new Autorizacao($service->get('Doctrine\ORM\EntityManager'));
                },
                'Application\Acl\PluginAutorizacao' => function ($service){
                return new PluginAutorizacao($service->get('Doctrine\ORM\EntityManager'));
                },
                'Application\Service\FuncaoAtividadeService' => function ($service){
                    return new FuncaoAtividadeService($service->get('Doctrine\ORM\EntityManager'));
                },
            ),
        );
    }
    /**
     * Registra as ViewHelpers
     * @return array ViewHelpers
     */
    public function getViewHelperConfig() {
        return array(
            'invokables' => array(
             	'Criptografia' => new Criptografia()
                //'UserIdentity' => new View\Helper\UserIdentity(),
                //'MontaMenu' => new View\Helper\MontaMenu(),
//                'FlashMessenger' => new View\Helper\FlashMessenger(),
            ),
            'factories' => array(
                // the array key here is the name you will call the view helper by in your view scripts
                'Menu' => function($sm) {
                    $locator = $sm->getServiceLocator(); // $sm is the view helper manager, so we need to fetch the main service manager
//                     return new Menu($locator->get('Request'));
                    return new Menu($locator->get('Doctrine\ORM\EntityManager'));
                },
            ),
        );
    }
    
    /**
     * MVC preDispatch Event
     *
     * @param $event
     * @return mixed
     */
    public function mvcPreDispatch($event) {
    	$application = $event->getApplication();
    	$services    = $application->getServiceManager();
    	$plAutorizacao = $services->get('Application\Acl\PluginAutorizacao');
    	$plAutorizacao->preDispatch($event);
    }

}
